// 将状态同步到url query中

// TODO 引入其他路由库
import { reactive, watchEffect } from "vue"

export function useUrlState<T>(data: { [key: string]: T }) {
  const copy = JSON.parse(JSON.stringify(data));

  const reactiveData = reactive(data);

  watchEffect(() => {
    const queryString = Object.entries(reactiveData).map(([k, v]) => `${k}=${v}`).join("&");
    let hash = location.hash;
    hash = hash.replace(/\?.*/, "");
    const url = `${location.origin}${location.pathname}${hash}?${queryString}`
    history.replaceState(null, '', url)
  })

  function reset() {
    Object.keys(reactiveData).forEach(key => {
      reactiveData[key] = copy[key];
    })
  }

  function clear() {
    let hash = location.hash;
    hash = hash.replace(/\?.*/, "");
    const url = `${location.origin}${location.pathname}${hash}`
    history.replaceState(null, '', url)
  }

  return { data: reactiveData, reset, clear }
}
